// pages/coupon/buycoupon/index.js
import {
  getCouponById
} from '../../../sers/coupon/coupon';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupon: null,
    tittop: app.globalData.tittop + 'rpx',
    lbtop: app.globalData.lbtop + 'rpx',
    isWindows: app.globalData.isWindows,
    remark: '',
    isExpanded: false,
    showExpandBtn: true,
    isShowPop: false,
    isShowPopAuth: false,
    disShowPop: false,
    checked: false,
  },
  onReady() {
    this.checkTextOverflow();
  },

  toggleText() {
    this.setData({
      isExpanded: !this.data.isExpanded,
      showExpandBtn: true
    });
  },

  checkTextOverflow() {
    const query = this.createSelectorQuery();
    query.select('.text-ellipsis').boundingClientRect(res => {
      if (res && res.height > 0) {
        // 估算 5 行高度（假设每行约 40rpx）
        const lineHeight = 40;
        const maxHeight = lineHeight * 5;

        // 判断是否超过 5 行
        if (res.height > maxHeight) {
          this.setData({
            showExpandBtn: true
          });
        }
      }
    }).exec();
  },
  // 定义分享内容
  onShareAppMessage() {
    return {
      title: '分享一个好物',
      path: `/pages/index/index?fromShare=1&couponId=${this.data.coupon.couponId}`, // 关键：跳转到首页，并携带参数
      //   imageUrl: 'https://pic.nximg.cn/20140101/10080014_193120762000_2.jpg'
    };
    // return {
    //   title: this.data.coupon.couponName,
    //   path: '/pages/coupon/buycoupon/index?couponId='+this.data.coupon.couponId,
    //   imageUrl: '',
    //   success: function (res) {
    //     console.log('分享成功', res);
    //     wx.showToast({ title: '分享成功' });
    //   },
    //   fail: function (res) {
    //     console.log('分享失败', res);
    //     wx.showToast({ title: '分享取消或失败' });
    //   }
    // };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    getCouponById(options.couponId).then(coupon => {
      console.log("2134325435")
      console.log(coupon.data);
      var temp = coupon.data.remark;
      var temp1 = temp.replace(/\\n/g, '\n');
      this.setData({
        remark: temp1
      });
      this.setData({
        coupon: coupon.data
      });
      console.log(this.data.coupon.couponId)
    }).catch(error => {
      console.log(error);
    });
  },
  // 点击券未登录提示
  buyCouponHandle(e) {
    console.log("kkk")
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      console.log("kkkk")
      let id = e.detail.id;
      //   this.setData({
      //     isShowPop:true
      //   });
      wx.navigateTo({
        url: '/pages/coupon/buycoupon/index?couponId=' + id,
      });
    } else {
      let id = e.detail.id;
      var couponTemp;
      for (var i = 0; i < this.data.couponList.length; ++i) {
        if (this.data.couponList[i].couponId == id) {
          couponTemp = this.data.couponList[i];
        }
      }
      if (couponTemp.type == 2) {
        if (this.data.userInfo.point < couponTemp.value) {
          app.showToast('积分不够，请积分足够时再试试。。。')
        } else {
          wx.navigateTo({
            url: '/pages/coupon/buycoupon/index?couponId=' + id,
          });
        }
      } else {
        wx.navigateTo({
          url: '/pages/coupon/buycoupon/index?couponId=' + id,
        });
      }
    }
  },
  //确认授权
  modalCancel(e) {
    console.log('进入modalCancel');
    this.setData({
      disShowPop: false
    });
  },
  modalConfirm(e) {
    console.log('进入modalConfirm');
    this.setData({
      disShowPop: false
    });
    // this.toLogin();
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      console.log("kkkkkk")
      this.setData({
        isShowPopAuth: true
      });
      // wx.showModal({
      //   title: '温馨提示',
      //   content: '授权用户信息',
      //   confirmText: '确认',
      //   cancelText: '暂不',
      //   success: (result) => {
      //     if (result.confirm) {
      //       wx.navigateTo({
      //         url: "/pages/login/login"
      //       });
      //     }
      //   }
      // });
    }

  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  /**
   * 登录授权事件
   */
  checkedPoint(e) {
    if (this.data.checked === false) {
      this.setData({
        checked: true,
        disShowPop: false,
      });
      this.get_user_info_event();
    }
  },
  /**
   * 登录授权事件
   */
  get_user_phone_event(e) {
    if (this.data.checked === false) {
      this.setData({
        disShowPop: true
      })
    } else if (this.data.checked === true) {
      this.user_auth_phone(e.detail);
    }
    // this.user_auth_phone(e.detail);
  },
  /**
   * 登录授权事件
   */
  get_user_info_event_(e) {
    this.setData({
      checked: true,
      disShowPop: false,
    });
    this.user_auth_code(e.detail);
  },
  get_user_info_event(e) {
    if (this.data.checked === false) {
      this.setData({
        disShowPop: true,
      });
    } else if (this.data.checked === true) {
      this.user_auth_code(e.detail);
    }
  },

  cance_btn() {
    this.setData({
      disShowPop: false
    })
  },
  /**
   * 用户授权
   * auth_data  授权数据
   */
  user_auth_code(auth_data) {
    //console.log("user_auth_code");
    if ((auth_data.encryptedData || null) != null && (auth_data.iv || null) != null) {
      console.log("aaaa")
      app.user_auth_login(this, 'user_auth_back_event', auth_data);
    } else {
      app.showToast("授权失败");
    }
  },

  /**
   * 授权返回事件
   */
  user_auth_back_event() {
    //console.log("user_auth_back_event");
    var user = app.get_user_cache_info();
    this.setData({
      user: user || null
    });
    // wx.showToast({
    //   icon: "none",
    //   title: '请继续点击获取手机号',
    // });
    //  this.setData({
    //     disShowUserPop: true,
    // })
    // 2. 获取用户信息成功后，自动触发获取手机号的隐藏按钮
    const phoneButton = this.selectComponent("#hiddenPhoneButton");
    console.log(phoneButton)
    console.log(phoneButton)
    if (phoneButton) {
      phoneButton.click(); // 此举会触发手机号授权弹窗
    } else {
      // this.setData({
      //     disShowUserPop: true,
      // })
      // 备用方案：如果无法直接操作组件，可以提示用户进行下一步操作
      //    wx.showModal({
      //      content: "请授权手机号以完成登录",
      //      success(res) {
      //        if (res.confirm) {
      //          // 这里可以引导用户点击一个实际显示的手机号授权按钮
      //        }
      //      },
      //    });
    }

    if (app.user_is_need_login(user) == false) {
      //  wx.navigateBack();
    }
  },




  /**
   * 用户授权
   * auth_data  授权数据
   */
  user_auth_phone(auth_data) {
    console.log(this.data.checked)
    console.log("user_auth_phone")
    if ((auth_data.encryptedData || null) != null && (auth_data.iv || null) != null) {
      app.user_auth_login_getPhone(this, 'user_auth_phone_back_event', auth_data);
    } else {
      app.showToast("手机授权失败");
    }
  },

  /**
   * 授权返回事件
   */
  user_auth_phone_back_event() {
    console.log("user_auth_phone_back_event");
    var user = app.get_user_cache_info();
    // var rcode = wx.getStorageSync("index_rcode");
    var rcode = app.globalData.rcode;
    console.log('rcode')
    console.log(rcode)
    if (rcode == null || rcode == '') {
      rcode = '';
    }
    this.setData({
      user: user || null,
      mobile: user.mobile,
      disShowPop: false
    });
    app.mobile = user.mobile;
    // if (app.user_mobile_check(user) == false) {
    // wx.navigateBack();
    // wx.navigateBack({
    //   success: res => {
    //     let pages = getCurrentPages();
    //     let prevPage = pages[pages.length - 1];      // 上一个页面的对象
    //     // 当然, 也可以通过setData设置那个页面的其他数据
    //     prevPage.onLoad();    // 触发上一个页面的onLoad生命周期函数
    //   }
    // });
    // }
    wx.request({
      url: app.get_request_url("savemember", "user"),
      method: "POST",
      data: {
        'memberName': '',
        'memberSex': '',
        'mobile': user.mobile,
        'address': '',
        'memberId': '',
        'rcode': rcode,
      },
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        var data = res.data.data;
        app.globalData.userInfo = data;
        wx.setStorageSync('cache_user_info', data);
        wx.showToast({
          icon: "none",
          title: '登录成功！',
        });
        wx.reLaunch({
          url: "/pages/index/index"
        });
        // wx.showModal({
        //   title: '提示',
        //   content: '注册/登录成功！',
        //   showCancel: false,
        //   success: function (res) {

        //     if (res.confirm) {
        //       // wx.navigateBack({
        //       //   success: res => {
        //       //     let pages = getCurrentPages();
        //       //     let prevPage = pages[pages.length - 1];      // 上一个页面的对象
        //       //     // 当然, 也可以通过setData设置那个页面的其他数据
        //       //     prevPage.onLoad();    // 触发上一个页面的onLoad生命周期函数
        //       //   }
        //       // });
        //       wx.reLaunch({
        //         url: "/pages/index/index"
        //       });
        //     }
        //   }
        // });
      },
      fail: () => {
        app.showToast("服务器请求出错");
      },
    });
  },

  get_user_phone_cancel() {

    // wx.navigateBack();
    try {
      wx.clearStorageSync();
    } catch (e) {}
    app.globalData.userInfo = null;
    this.setData({
      userInfo: null,
      isShowPopAuth: false,
      user: null,
      checked: false
    });
    // wx.reLaunch({
    //   url: '/pages/index/index?op=exithmb'
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  //   onShareAppMessage() {

  //   },

  submitBuyP(e) {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    console.log(user)
    if (user == null) {
      console.log("lll")
      this.setData({
        isShowPopAuth: true
      })
      // wx.navigateTo({
      //     url: "/pages/usercenter/updateMember/index"
      //   });
    } else {
      var that = this;
      if (that.data.coupon.canReceive == false) {
        wx.showModal({
          title: '提示',
          content: '已售罄,请选择其它券购买',
          showCancel: false,
          success: function (res) {

          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '确认是否购买',
          showCancel: true,
          success: function (res) {
            if (res.confirm) {
              that.receivecoupon();
            }
          }
        });
      }
    }

  },

  submitBuyR(e) {
    var that = this;
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    if (user == null) {
      console.log("lll")
      this.setData({
        isShowPopAuth: true
      })
    } else {
      if (that.data.coupon.canReceive == false) {
        wx.showModal({
          title: '提示',
          content: '已领完,请选择其它券领用',
          showCancel: false,
          success: function (res) {

          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '确认是否领用',
          showCancel: true,
          success: function (res) {
            if (res.confirm) {
              that.receivecoupon();
            }
          }
        });
      }
    }

  },

  submitBuyC(e) {
    var that = this;
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    if (user == null) {
      console.log("lll")
      this.setData({
        isShowPopAuth: true
      })
    } else {
      if (that.data.coupon.canReceive == false) {
        wx.showModal({
          title: '提示',
          content: '已兑完,请选择其它券兑换',
          showCancel: false,
          success: function (res) {

          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '确认是否兑换',
          showCancel: true,
          success: function (res) {
            if (res.confirm) {
              that.receivecoupon();
            }
          }
        });
      }
    }
  },

  receivecoupon() {
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != nul) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    wx.request({
      url: app.get_request_url("receivecoupon", "coupons"),
      method: "POST",
      data: {
        couponId: this.data.coupon.couponId,
        mobile: mobile,
        couponType: this.data.coupon.couponType,
        value: this.data.coupon.value == null ? '' : this.data.coupon.value,
        couponName: this.data.coupon.couponName,
        type: this.data.coupon.type,
      },
      dataType: "json",
      success: res => {
        if (res.data.code == 0) {
          if (this.data.coupon.type == 1) {
            wx.hideLoading();
            app.showToast("领取成功");
            setTimeout(function () {
              wx.navigateBack({
                success: res => {
                  wx.reLaunch({
                    url: '/pages/index/index'
                  })
                }
              });
            }, 2000);
          } else if (this.data.coupon.type == 2) {
            wx.hideLoading();
            app.showToast("兑换成功");
            setTimeout(function () {
              wx.navigateBack({
                success: res => {
                  wx.reLaunch({
                    url: '/pages/index/index'
                  })
                }
              });
            }, 2000);
          } else {
            this.wxPay(res.data.data);
          }
        } else {
          wx.hideLoading();
          app.showToast(res.data.msg);
        }
      },

      fail: () => {
        wx.hideLoading();
        app.showToast("服务器请求出错");
      }
    });
  },

  wxPay(payParams) {
    var that = this
    wx.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign,
      success: function (res) {
        wx.request({
          url: app.get_request_url("paySuccess", "coupons"),
          method: "POST",
          data: {
            merOrderNo: payParams.merOrderNo,
          },
          dataType: "json",
          success: res => {
            wx.hideLoading();
          },
          fail: () => {
            wx.hideLoading();
          }
        });

        // 跳转支付页面
        wx.navigateTo({
          url: "/pages/paytips/paytips?code=9000&total_price=" + that.data.coupon.value
        });
      },
      fail: function (res) {
        app.showToast('支付失败');
      }
    });
  },

  toBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },
})